"""
日志插件使用示例
演示如何使用日志插件记录和查询日志
"""
import requests
import json
from datetime import datetime, timedelta
import time

# 基础URL
BASE_URL = "http://localhost:8000"

def test_logger_plugin():
    """测试日志插件的各种功能"""
    
    print("=== 日志插件使用示例 ===\n")
    
    # 1. 记录不同类型的日志
    print("1. 记录各种类型的日志...")
    
    log_entries = [
        {
            "level": "INFO",
            "message": "用户登录成功",
            "source": "auth",
            "details": {"user_id": 123, "ip": "192.168.1.100"}
        },
        {
            "level": "WARNING",
            "message": "数据库连接超时",
            "source": "database",
            "details": {"timeout": 30, "retry_count": 3}
        },
        {
            "level": "ERROR",
            "message": "文件上传失败",
            "source": "upload",
            "details": {"file_size": "10MB", "error": "磁盘空间不足"}
        },
        {
            "level": "DEBUG",
            "message": "开始处理用户请求",
            "source": "api",
            "details": {"endpoint": "/api/users", "method": "GET"}
        },
        {
            "level": "INFO",
            "message": "系统启动完成",
            "source": "system",
            "details": {"version": "1.0.0", "startup_time": "2.5s"}
        }
    ]
    
    for entry in log_entries:
        response = requests.post(f"{BASE_URL}/logger/log", json=entry)
        if response.status_code == 200:
            print(f"✓ 记录日志: {entry['level']} - {entry['message']}")
        else:
            print(f"✗ 记录日志失败: {response.text}")
    
    print()
    
    # 2. 查询所有日志
    print("2. 查询所有日志...")
    response = requests.get(f"{BASE_URL}/logger/logs")
    if response.status_code == 200:
        data = response.json()
        print(f"总日志数: {data['total']}")
        print(f"返回日志数: {data['count']}")
        print("最近的日志:")
        for log in data['logs'][:3]:  # 只显示前3条
            print(f"  [{log['timestamp']}] {log['level']} - {log['source']}: {log['message']}")
    else:
        print(f"查询日志失败: {response.text}")
    
    print()
    
    # 3. 按级别查询日志
    print("3. 查询ERROR级别的日志...")
    response = requests.get(f"{BASE_URL}/logger/logs?level=ERROR")
    if response.status_code == 200:
        data = response.json()
        print(f"ERROR级别日志数: {data['count']}")
        for log in data['logs']:
            print(f"  [{log['timestamp']}] {log['level']} - {log['source']}: {log['message']}")
    else:
        print(f"查询ERROR日志失败: {response.text}")
    
    print()
    
    # 4. 按来源查询日志
    print("4. 查询来自'system'的日志...")
    response = requests.get(f"{BASE_URL}/logger/logs?source=system")
    if response.status_code == 200:
        data = response.json()
        print(f"system来源日志数: {data['count']}")
        for log in data['logs']:
            print(f"  [{log['timestamp']}] {log['level']} - {log['source']}: {log['message']}")
    else:
        print(f"查询system日志失败: {response.text}")
    
    print()
    
    # 5. 获取日志统计
    print("5. 获取日志统计信息...")
    response = requests.get(f"{BASE_URL}/logger/stats")
    if response.status_code == 200:
        stats = response.json()
        print(f"总日志数: {stats['total_logs']}")
        print("按级别统计:")
        for level, count in stats['logs_by_level'].items():
            print(f"  {level}: {count}")
        print("按来源统计:")
        for source, count in stats['logs_by_source'].items():
            print(f"  {source}: {count}")
    else:
        print(f"获取统计信息失败: {response.text}")
    
    print()
    
    # 6. 获取支持的日志级别
    print("6. 获取支持的日志级别...")
    response = requests.get(f"{BASE_URL}/logger/levels")
    if response.status_code == 200:
        data = response.json()
        print(f"支持的日志级别: {', '.join(data['levels'])}")
    else:
        print(f"获取日志级别失败: {response.text}")
    
    print()
    
    # 7. 获取所有日志来源
    print("7. 获取所有日志来源...")
    response = requests.get(f"{BASE_URL}/logger/sources")
    if response.status_code == 200:
        data = response.json()
        print(f"日志来源: {', '.join(data['sources'])}")
    else:
        print(f"获取日志来源失败: {response.text}")
    
    print()
    
    # 8. 导出日志
    print("8. 导出日志为JSON格式...")
    response = requests.get(f"{BASE_URL}/logger/export?format=json")
    if response.status_code == 200:
        data = response.json()
        print(f"导出格式: {data['format']}")
        print(f"导出日志数: {data['count']}")
        print("导出的前100个字符:")
        print(data['data'][:100] + "...")
    else:
        print(f"导出日志失败: {response.text}")
    
    print()
    
    # 9. 导出日志为文本格式
    print("9. 导出日志为文本格式...")
    response = requests.get(f"{BASE_URL}/logger/export?format=text")
    if response.status_code == 200:
        data = response.json()
        print(f"导出格式: {data['format']}")
        print(f"导出日志数: {data['count']}")
        print("导出的前200个字符:")
        print(data['data'][:200] + "...")
    else:
        print(f"导出日志失败: {response.text}")
    
    print()
    
    # 10. 分页查询
    print("10. 分页查询日志...")
    response = requests.get(f"{BASE_URL}/logger/logs?limit=2&offset=0")
    if response.status_code == 200:
        data = response.json()
        print(f"第1页 (limit=2, offset=0): {data['count']} 条日志")
        for log in data['logs']:
            print(f"  [{log['timestamp']}] {log['level']} - {log['source']}: {log['message']}")
        
        response2 = requests.get(f"{BASE_URL}/logger/logs?limit=2&offset=2")
        if response2.status_code == 200:
            data2 = response2.json()
            print(f"第2页 (limit=2, offset=2): {data2['count']} 条日志")
            for log in data2['logs']:
                print(f"  [{log['timestamp']}] {log['level']} - {log['source']}: {log['message']}")
    else:
        print(f"分页查询失败: {response.text}")

def test_logger_integration():
    """测试日志插件与其他插件的集成"""
    
    print("\n=== 日志插件集成测试 ===\n")
    
    # 测试与计算器插件的集成
    print("1. 测试与计算器插件的集成...")
    
    # 记录计算器操作
    calc_operations = [
        {"operation": "add", "a": 10, "b": 5},
        {"operation": "multiply", "a": 7, "b": 8},
        {"operation": "divide", "a": 100, "b": 4}
    ]
    
    for op in calc_operations:
        # 记录操作开始
        requests.post(f"{BASE_URL}/logger/log", json={
            "level": "INFO",
            "message": f"开始计算: {op['operation']}({op['a']}, {op['b']})",
            "source": "calculator",
            "details": op
        })
        
        # 执行计算
        response = requests.post(f"{BASE_URL}/calculator/{op['operation']}", json=op)
        
        if response.status_code == 200:
            result = response.json()
            # 记录操作成功
            requests.post(f"{BASE_URL}/logger/log", json={
                "level": "INFO",
                "message": f"计算成功: {result['result']}",
                "source": "calculator",
                "details": result
            })
            print(f"✓ {op['operation']}({op['a']}, {op['b']}) = {result['result']}")
        else:
            # 记录操作失败
            requests.post(f"{BASE_URL}/logger/log", json={
                "level": "ERROR",
                "message": f"计算失败: {response.text}",
                "source": "calculator",
                "details": {"operation": op, "error": response.text}
            })
            print(f"✗ 计算失败: {response.text}")
    
    print()
    
    # 查询计算器相关的日志
    print("2. 查询计算器相关的日志...")
    response = requests.get(f"{BASE_URL}/logger/logs?source=calculator")
    if response.status_code == 200:
        data = response.json()
        print(f"计算器相关日志数: {data['count']}")
        for log in data['logs']:
            print(f"  [{log['timestamp']}] {log['level']} - {log['source']}: {log['message']}")
    else:
        print(f"查询计算器日志失败: {response.text}")

def test_logger_advanced_features():
    """测试日志插件的高级功能"""
    
    print("\n=== 日志插件高级功能测试 ===\n")
    
    # 1. 测试时间范围查询
    print("1. 测试时间范围查询...")
    
    # 获取当前时间
    now = datetime.now()
    one_hour_ago = now - timedelta(hours=1)
    
    response = requests.get(f"{BASE_URL}/logger/logs", params={
        "start_time": one_hour_ago.isoformat(),
        "end_time": now.isoformat()
    })
    
    if response.status_code == 200:
        data = response.json()
        print(f"最近1小时的日志数: {data['count']}")
    else:
        print(f"时间范围查询失败: {response.text}")
    
    print()
    
    # 2. 测试复杂查询
    print("2. 测试复杂查询（INFO级别 + system来源）...")
    response = requests.get(f"{BASE_URL}/logger/logs?level=INFO&source=system")
    if response.status_code == 200:
        data = response.json()
        print(f"符合条件的日志数: {data['count']}")
        for log in data['logs']:
            print(f"  [{log['timestamp']}] {log['level']} - {log['source']}: {log['message']}")
    else:
        print(f"复杂查询失败: {response.text}")

if __name__ == "__main__":
    try:
        # 运行基本功能测试
        test_logger_plugin()
        
        # 运行集成测试
        test_logger_integration()
        
        # 运行高级功能测试
        test_logger_advanced_features()
        
        print("\n=== 所有测试完成 ===")
        
    except requests.exceptions.ConnectionError:
        print("错误: 无法连接到服务器，请确保FastAPI应用正在运行")
        print("运行命令: python main.py")
    except Exception as e:
        print(f"测试过程中发生错误: {e}") 